package com.client.elements.normal;

import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class Table {

	public static FlexTable table = new FlexTable();
	public static ScrollPanel scroll = new ScrollPanel(table);
	public static Widget table() {
		final TextBox anzahl = new TextBox();
		FlowPanel panel = new FlowPanel();

		FlowPanel p = new FlowPanel();
		p.setSize("10px","10px");
		panel.add(anzahl);
		panel.add(p);
		panel.add(scroll);

		anzahl.setText("5");
		anzahl.addKeyUpHandler(new KeyUpHandler() {
			@Override
			public void onKeyUp(KeyUpEvent event) {
				Integer i = ueberpruefeEingabe(anzahl.getValue());
				if (i != null) {
					anzahl.removeStyleName("red_Background");						
					if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
						erzeugeTabelle(i);
					}	
				}else {
					anzahl.addStyleName("red_Background");
				}
			}
		});
		return panel;
	}

	private static Integer ueberpruefeEingabe(String n){
		try {
			int i = Integer.parseInt(n);
			if (i == 0) {
				return null;
			}
			return i;
		} catch (NumberFormatException e) {
			return null;
		}
	}

	private static void erzeugeTabelle(int i){
		table.removeAllRows();
		for (int row = 0; row < i + 1; row++) {
			for (int column = 0; column < i + 1; column++) {
				if ((row == 0)&&(column == 0)) {
					table.setText(row, column, "");
				}else if (row == 0) {
					table.setHTML(row, column, "<b>c" + column + "<b>");
				}else if (column == 0) {
					table.setHTML(row, column, "<b>r" + row + "<b>");
				}else {
					table.setText(row, column, row + "." + column);
				}
			}
		}
		table.setCellPadding(5);
		table.setCellSpacing(2);
		table.setBorderWidth(2);
		table.getColumnFormatter().addStyleName(0, "tableHeader");
		table.getRowFormatter().addStyleName(0, "tableHeader");
		scroll.setSize("300px", "300px");
	}
}